#include <iostream>
using namespace std;
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(char *proc)
{
    cout << "Usage:\n\t" << proc << "  server_ip  server_port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string server_ip = argv[1];
    uint16_t server_port = stoi(argv[2]);

    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    int sockfd = socket(AF_INET, SOCK_STREAM, 0); //
    if (sockfd < 0)
    {
        cout << __LINE__ << " : socket error" << endl;
        exit(2);
    }

    // 0. connect
    int m = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (m < 0)
    {
        cout << __LINE__ << " : connect error" << endl;
        exit(3);
    }
    cout << __LINE__ << " : connect success" << endl;

    while (true)
    {
        // 1. 发消息
        cout << "Please Enter# ";
        string message;
        getline(cin, message);
        ssize_t n = send(sockfd, message.c_str(), message.size(), 0);
        if (n < 0)
        {
            cout << __LINE__ << " : send error" << endl;
            break;
        }
        cout << __LINE__ << " : send success" << endl;

        // 2. 收消息
        cout << "Server echo# ";
        char buffer[1024];
        n = recv(sockfd, buffer, 1024, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
    }

    return 0;
}